#!/bin/bash

# obtain model
get_model &>/dev/null

ubuntu_pios_chromium_available=0
if [[ "$model" == *"Raspberry Pi"* ]] && [[ "$__os_id" == Ubuntu ]] && printf '%s\n' "22.04" "$__os_release" | sort -CV; then
  ubuntu_pios_chromium_available=1
  # Ubuntu must be 22.10+ (GLIBC 2.36+) to be compatible with widevine
  pin_hide_widevine=1
  if printf '%s\n' "22.10" "$__os_release" | sort -CV; then
    pin_hide_widevine=0
  fi
fi

#determine if chromium is installed
if command -v chromium >/dev/null || command -v chromium-browser >/dev/null || [ -d /snap/chromium ] || [ -d /var/lib/flatpak/app/org.chromium.Chromium ];then
  echo "Chromium is installed. Continuing..."
# chromium is not installed but PiOS chromium could be installed
elif [[ "$ubuntu_pios_chromium_available" == 1 ]]; then
  if [[ "$pin_hide_widevine" == 0 ]]; then
    description="Chromium is not installed but the PiOS chromium browser is available and is faster and supports widevine. Install it?"
  else
    description="Chromium is not installed but the PiOS chromium browser is available and is faster. Install it?"
  fi
  userinput_func "$description" "Yes, install PiOS chromium" "No, exit Better Chromium now"
  if [ "$output" == "No, exit Better Chromium now" ]; then
    error "User error: Chromium is not installed and you choose not to install PiOS chromium! Failed to find either a 'chromium' command or 'chromium-browser' command. If you are sure Chromium is installed, please reach out to Botspot for this to be fixed."
  fi
else
  error "User error: Chromium is not installed! Failed to find either a 'chromium' command or 'chromium-browser' command. If you are sure Chromium is installed, please reach out to Botspot for this to be fixed."
fi

#install PiOS chromium on Raspberry Pi Ubuntu
if [[ "$ubuntu_pios_chromium_available" == 1 ]]; then
  if [[ "$pin_hide_widevine" == 0 ]]; then
    description="The PiOS chromium browser is faster and supports widevine. Install it?"
  else
    description="The PiOS chromium browser is faster. Install it?"
  fi
  if [ -d /snap/chromium ]; then
    userinput_func "$description" "Yes, uninstall Ubuntu snap chromium and install PiOS chromium" "No, leave my Ubuntu snap chromium untouched"
  elif [ -d /var/lib/flatpak/app/org.chromium.Chromium ]; then
    userinput_func "$description" "Yes, uninstall flatpak chromium and install PiOS chromium" "No, leave my flatpak chromium untouched"
  else
    # do not prompt user again for installing PiOS chromium when they do not currently have the snap or flatpak installed
    output="Yes, install PiOS chromium"
  fi
  if [[ "$output" == "Yes"* ]]; then
    # rpi ubuntu (22.04+) use Pi OS packaged chromium for better hardware support
    add_external_repo "pi-apps-coders-chromium" "https://github.com/Pi-Apps-Coders/chromium-debs/raw/main/KEY.gpg" "https://github.com/Pi-Apps-Coders/chromium-debs/releases/download/apt-release" "./" || exit 1
    # also disable chromium snap apt package from Ubuntu
    if [[ "$pin_hide_widevine" == 0 ]]; then
     echo 'Package: chromium-*
Pin: release o=Pi-Apps-Coders chromium-debs
Pin-Priority: 1000

Package: libwidevinecdm0
Pin: release o=Pi-Apps-Coders chromium-debs
Pin-Priority: 500

Package: chromium-*
Pin: release o=Ubuntu*
Pin-Priority: -1' | sudo tee /etc/apt/preferences.d/pi-apps-coders-chromium >/dev/null
    else
      echo 'Package: chromium-*
Pin: release o=Pi-Apps-Coders chromium-debs
Pin-Priority: 1000

Package: libwidevinecdm0
Pin: release o=Pi-Apps-Coders chromium-debs
Pin-Priority: -1

Package: chromium-*
Pin: release o=Ubuntu*
Pin-Priority: -1' | sudo tee /etc/apt/preferences.d/pi-apps-coders-chromium >/dev/null
    fi
    # regular apt installs will not switch an already installed 1:1snap* package to a XXX chromium-browser package since this would constitute a downgrade
    # the pin priorities added above will prevent Ubuntu repository chromium-browser packages from even showing or installing in the future but we still need to do the initial downgrade from 1:1snap* to the Pi OS version of chromium-browser
    apt_update
    apt_lock_wait
    sudo apt --allow-downgrades install chromium-browser -y | less_apt
    # remove snap chromium
    [ -d /snap/chromium ] && sudo snap remove chromium
    # remove flatpak chromium
    [ -d /var/lib/flatpak/app/org.chromium.Chromium ] && sudo flatpak uninstall org.chromium.Chromium -y
    # copy snap or flatpak chromium config over to ~/.config/chromium if it does not already exist
    if [ ! -d ~/.config/chromium ]; then
      mkdir -p ~/.config
      if [ -d ~/snap/chromium/current/.config/chromium ]; then
        cp -R ~/snap/chromium/current/.config/chromium ~/.config/
      elif [ -d ~/snap/chromium/common/chromium ]; then
        cp -R ~/snap/chromium/common/chromium ~/.config/
      elif [ -d ~/.var/app/org.chromium.Chromium/config/chromium ]; then
        cp -R ~/.var/app/org.chromium.Chromium/config/chromium ~/.config/
      fi
    fi
    # add apparmor profile if needed
    if sysctl kernel.apparmor_restrict_unprivileged_userns | grep -q 1 ; then
      echo '# This profile allows everything and only exists to give the
# application a name instead of having the label "unconfined"

abi <abi/4.0>,
include <tunables/global>

profile chromium-browser /usr/lib/chromium-browser/chromium-browser flags=(unconfined) {
  userns,

  # Site-specific additions and overrides. See local/README for details.
  include if exists <local/chromium-browser>
}
' | sudo tee /etc/apparmor.d/chromium-browser >/dev/null
      sudo systemctl restart apparmor.service
    fi
  fi
fi

#determine where the Chromium customizations folder is.
if [ -d /etc/chromium.d ];then
  folder=/etc/chromium.d
  
elif [ -d /snap/chromium ] && [ -f /snap/bin/chromium ];then
  #if Snap Chromium is installed, make the customizations folder and later make a script to source its contents
  if [ ! -d /etc/chromium.d ];then
    sudo mkdir -p /etc/chromium.d
  fi
  folder=/etc/chromium.d
  
elif [ -d /etc/chromium-browser ];then
  sudo mkdir -p /etc/chromium-browser/customizations
  folder=/etc/chromium-browser/customizations
elif [ -d /etc/chromium-browser-stable ];then
  sudo mkdir -p /etc/chromium-browser-stable/customizations
  folder=/etc/chromium-browser-stable/customizations
elif [ -d /etc/chromium-browser-beta ];then
  sudo mkdir -p /etc/chromium-browser-beta/customizations
  folder=/etc/chromium-browser-beta/customizations
elif [ -d /etc/chromium-browser-unstable ];then
  sudo mkdir -p /etc/chromium-browser-unstable/customizations
  folder=/etc/chromium-browser-unstable/customizations
  
else
  error "User error (reporting allowed): Cannot find the directory where Chromium keeps its flags! Usually this would be /etc/chromium.d or /etc/chromium-browser/customizations. On your system, neither of these directories exist. Please reach out to Botspot for this to be fixed."
fi

#Fix edge case where both an old version of chromium and a newer version are installed simultaneously
if [ -d /etc/chromium-browser/customizations ] && [ -d /etc/chromium.d ] && [ ! -L /etc/chromium-browser/customizations ];then
  #The $folder variable is /etc/chromium.d, but make /etc/chromium-browser/customizations pick up changes in /etc/chromium.d by using a symlink
  
  status -n "There are two Chromium customization folders on your system: /etc/chromium.d and /etc/chromium-browser/customizations.\nCreating a symlink to keep both locations synchronized..."
  
  #Move any customization files from /etc/chromium-browser/customizations to /etc/chromium.d, without overwriting anything
  sudo cp -nr /etc/chromium-browser/customizations /etc/chromium.d && \
  sudo rm -rf /etc/chromium-browser/customizations && \
  sudo ln -s /etc/chromium.d /etc/chromium-browser/customizations
  
  status_green Done
fi

#if Chromium is installed from Snap or Flatpak, make a script to source the contents of /etc/chromium.d
if [ -d /snap/chromium ] || [ -d /var/lib/flatpak/app/org.chromium.Chromium ];then
  if [ -f $HOME/.chromium-browser.init ] && [ "$(sha1sum $HOME/.chromium-browser.init | awk '{print $1}')" != 'cead3a7e98ddd3dbfeea285736c89409a7d426cd' ];then
    warning "This script needs to create this file: ~/.chromium-browser.init, but it already exists!"
    read -N 1 -p "Enter Y to replace this file, or N to exit now." answer
    echo
    
    if [ "$answer" != Y ] && [ "$answer" != y ];then
      echo "User error: $HOME/.chromium-browser.init already exists and the user did not want to overwrite it."
      exit 1
    fi
  fi
  
  #The ~/.chromium-browser.init file is the one single entrypoint for running scripts during a Snap Chromium's launch.
  #I encountered significant difficulty making this work. Normal Chromium-browser uses bash to source things, but Snap /snap/chromium/2003/bin/chromium.launcher is /bin/sh
  cat << "EOF" > $HOME/.chromium-browser.init
#!/bin/sh
eval "$(run-parts --list -- /etc/chromium.d | xargs cat)"
EOF
fi

#remove deprecated tab previews customization file, not that it is the default on latest chromium
sudo rm -f "${folder}/tab_previews"

#detect if dark mode is currently enabled by this tool
if [ -f "${folder}/dark_mode" ];then
  dark_mode=TRUE
else
  dark_mode=FALSE
fi

#detect if dark mode for all websites is currently enabled by this tool
if [ -f "${folder}/site_dark_mode"  ];then
  site_dark_mode=TRUE
else
  site_dark_mode=FALSE
fi

#detect current UI scale value
if [ -f "${folder}/ui_scale" ];then
  ui_scale="$(cat "${folder}/ui_scale" | grep -o '\--force-device-scale-factor=.*' | tr -cd '0123456789.\n')"
else
  ui_scale=1.00
fi

#detect if tab scrolling is enabled
if [ -f "${folder}/tab_scrolling" ];then
  tab_scrolling=TRUE
else
  tab_scrolling=FALSE
fi

#detect if google sync is currently enabled by this tool
if [ -f "${folder}/apikeys" ];then
  google_sync=TRUE
else
  google_sync=FALSE
fi

#detect if chromerefresh2023 is currently enabled by this tool
if [ -f "${folder}/chromerefresh2023" ];then
  chromerefresh2023=TRUE
else
  chromerefresh2023=FALSE
fi

#detect if various performance improvements are currently enabled by this tool
if [ -f "${folder}/performance_improvements" ];then
  performance_improvements=TRUE
else
  performance_improvements=FALSE
fi

#detect if the reduce_writes script is enabled
if [ -f "${folder}/reduce_writes" ];then
  reduce_writes=TRUE
else
  reduce_writes=FALSE
fi

#detect if Widevine is enabled
if [ -d /opt/WidevineCdm ];then
  widevine=TRUE
else
  widevine=FALSE
fi
#detect if Widevine can be enabled
if package_available libwidevinecdm0 && package_installed chromium-browser;then
  widevine_possible=TRUE
  widevine_message=(--field="Enable Widevine DRM (for Netflix, Spotify)":CHK "$widevine")
else
  widevine_possible=FALSE
  widevine_message=()
fi

#Set text of dialog window
text="<b>Better Chromium</b> - by Botspot"

#detect if chromium is running, and if so, remind the user to relaunch it when done
if pgrep chromium >/dev/null || pgrep -f chromium-browser >/dev/null ;then
  text+=$'\n'"Changes will take effect after you relaunch Chromium."
fi

output="$(yad --center --form --width=410 --separator='\n' \
  --title="Better Chromium" \
  --window-icon="$(dirname "$0")/icon-64.png" \
  --text="$text" \
  --field="Enable Dark Mode":CHK "$dark_mode" \
  --field="Dark Mode for all websites":CHK "$site_dark_mode" \
  --field="<a href="\""https://chrome.google.com/webstore/search/neon%20kingdom%20-tabs?_category=themes"\"">Click to see more themes</a>:LBL" '' \
  --field="UI Scale: (default 1)":NUM "${ui_scale}!0.25..4!0.05!2" \
  --field="New UI 2023":CHK "$chromerefresh2023" \
  --field="Tab Scrolling":CHK "$tab_scrolling" \
  --field="Enable Google Sync":CHK "$google_sync" \
  --field="Performance Improvements":CHK "$performance_improvements" \
  --field="Reduce SD card writes":CHK "$reduce_writes" \
  "${widevine_message[@]}")"

button=$?
if [ "$button" != 0 ];then
  echo "User error: Exiting now without making any changes."
  exit 1
fi

echo "Received values:"
dark_mode="$(sed -n 1p <<<"$output")"
echo "dark_mode: $dark_mode"
site_dark_mode="$(sed -n 2p <<<"$output")"
echo "site_dark_mode: $site_dark_mode"
#skip line 3 because that was an empty field from "Click to see more themes" links
ui_scale="$(sed -n 4p <<<"$output")"
echo "ui_scale: $ui_scale"
chromerefresh2023="$(sed -n 5p <<<"$output")"
echo "chromerefresh2023: $chromerefresh2023"
tab_scrolling="$(sed -n 6p <<<"$output")"
echo "tab_scrolling: $tab_scrolling"
google_sync="$(sed -n 7p <<<"$output")"
echo "google_sync: $google_sync"
performance_improvements="$(sed -n 8p <<<"$output")"
echo "performance_improvements: $performance_improvements"
reduce_writes="$(sed -n 9p <<<"$output")"
echo "reduce_writes: $reduce_writes"
widevine="$(sed -n 10p <<<"$output")"
echo "widevine: $widevine"
echo

#if user enabled reduce_writes or performance_improvements, and ZRAM is not installed, then recommend the More RAM app
if [ ! -f /usr/bin/zram.sh ] && [ "$performance_improvements" == TRUE ] ;then
  
  yad --center --width=410 --separator='\n' \
  --title="Better Chromium" \
  --window-icon="$(dirname "$0")/icon-64.png" \
  --text="You've chosen to improve Chromium's performance by adding a few flags to it. Further improvement is possible by installing the <b>More RAM</b> app on Pi-Apps. This increases usable RAM while avoiding a swap file." \
  --button="Thanks for the tip - I'll check out <b>More RAM</b>.":0 &>/dev/null &
elif [ ! -f /usr/bin/zram.sh ] && [ "$reduce_writes" == TRUE ] ;then
  
  yad --center --width=410 --separator='\n' \
  --title="Better Chromium" \
  --window-icon="$(dirname "$0")/icon-64.png" \
  --text="You've chosen to reduce writes to the SD card. Further improvement is possible by installing the <b>More RAM</b> app on Pi-Apps. This increases usable RAM while avoiding a swap file." \
  --button="Thanks for the tip - I'll check out <b>More RAM</b>.":0 &>/dev/null &
fi

#
#write changes to chromium flag folder
#
status "Writing changes..."
#add zzzz_combine_values script in all cases to combine --enable-features arguments
echo "Creating workaround script at ${folder}/zzzz_combine_values"
cat << "EOF" | sudo tee "${folder}/zzzz_combine_values" >/dev/null
#This script combines multiple invocations of --enable-features and --disable-features into one argument so that Chromium does not ignore any.
#Written by Botspot for the Pi-Apps Better Chromium script.

#Intercept chromium args and move them to CHROMIUM_FLAGS
while [ $# -gt 0 ]; do
  case "$1" in
    #Avoid passing chromium-browser script args to chromium-browser binary
    -h | --help | -help | --verbose | -g | --debug | --no-touch-pinch | --temp-profile | -- ) # Stop option prcessing
      break ;;
    * )
      CHROMIUM_FLAGS="$CHROMIUM_FLAGS $1"
      shift ;;
  esac
done

IFS=' '
enable=''
disable=''
new_flags=''
for word in $CHROMIUM_FLAGS ;do
  if echo "$word" | grep -q '^--enable-features=' ;then
    enable="${enable},$(echo "$word" | sed 's/^--enable-features=//g')"
  elif echo "$word" | grep -q '^--disable-features=' ;then
    disable="${disable},$(echo "$word" | sed 's/^--disable-features=//g')"
  else
    new_flags="$new_flags $word"
  fi
done

#remove initial comma
enable="$(echo "$enable" | sed 's/^,//g')"
disable="$(echo "$disable" | sed 's/^,//g')"

CHROMIUM_FLAGS="$new_flags"
[ ! -z "$enable" ] && CHROMIUM_FLAGS="$CHROMIUM_FLAGS --enable-features=$enable"
[ ! -z "$disable" ] && CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-features=$disable"
EOF

#dark mode
if [ "$dark_mode" == TRUE ];then
  #I found this flag on https://peter.sh/experiments/chromium-command-line-switches
  echo "Adding --force-dark-mode to ${folder}/dark_mode"
  
  cat << EOF | sudo tee "${folder}/dark_mode" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS --force-dark-mode"
EOF
else
  #dark mode set to false - so remove the file
  if [ -f "${folder}/dark_mode" ];then
    status "Removing ${folder}/dark_mode"
  fi
  sudo rm -f "${folder}/dark_mode"
fi

#dark mode for all websites
if [ "$site_dark_mode" == TRUE ];then
  #I found this flag on https://peter.sh/experiments/chromium-command-line-switches
  echo "Adding --enable-features=WebContentsForceDark:inversion_method/cielab_based/image_behavior/none/foreground_lightness_threshold/150/background_lightness_threshold/150 to ${folder}/site_dark_mode"
  
  cat << EOF | sudo tee "${folder}/site_dark_mode" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS --enable-features=WebContentsForceDark:inversion_method/cielab_based/image_behavior/none/foreground_lightness_threshold/150/background_lightness_threshold/150" #WebContentsForceDark:increase_text_contrast/true"
EOF
else
  #dark mode set to false - so remove the file
  if [ -f "${folder}/site_dark_mode" ];then
    status "Removing ${folder}/site_dark_mode"
  fi
  sudo rm -f "${folder}/site_dark_mode"
fi

#UI scale
if [ "$ui_scale" != 1.00 ];then
  #I found this flag on https://peter.sh/experiments/chromium-command-line-switches
  echo "Adding --device-scale-factor=${ui_scale} to ${folder}/ui_scale"
  
  cat << EOF | sudo tee "${folder}/ui_scale" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS --force-device-scale-factor=${ui_scale}"
EOF
else
  #ui scale set to 1.00 (default), so remove file
  if [ -f "${folder}/ui_scale" ];then
    status "Removing ${folder}/ui_scale"
  fi
  sudo rm -f "${folder}/ui_scale"
fi

#New 2023 chrome UI
if [ "$chromerefresh2023" == TRUE ];then
  #I found this flag after experimenting with chrome://flags and chrome://version
  echo "Adding --enable-features=ChromeRefresh2023,ChromeWebuiRefresh2023,ChromeRefresh2023NTB:Variation/GM3NewIconWithBackground,FluentScrollbar,FluentOverlayScrollbar,OverlayScrollbar --disable-features=ChromeLabs,SimplifiedBookmarkSaveFlow to ${folder}/chromerefresh2023"
  
  cat << EOF | sudo tee "${folder}/chromerefresh2023" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS --enable-features=ChromeRefresh2023,ChromeWebuiRefresh2023,ChromeRefresh2023NTB:Variation/GM3NewIconWithBackground,FluentScrollbar,FluentOverlayScrollbar,OverlayScrollbar --disable-features=ChromeLabs,SimplifiedBookmarkSaveFlow"
EOF
else
  #chromerefresh2023 set to false - so remove the file
  if [ -f "${folder}/chromerefresh2023" ];then
    status "Removing ${folder}/chromerefresh2023"
  fi
  sudo rm -f "${folder}/chromerefresh2023"
fi

#Tab scrolling
if [ "$tab_scrolling" == TRUE ];then
  #I found this flag after experimenting with chrome://flags and chrome://version
  echo "Adding --enable-features=ScrollableTabStrip:minTabWidth/140,TabScrollingButtonPosition:buttonPosition/2,kScrollableTabStripOverflow:tabScrollOverflow/2,kScrollableTabStripWithDragging:tabScrollWithDragMode/2 to ${folder}/tab_scrolling"
  
  cat << EOF | sudo tee "${folder}/tab_scrolling" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS --enable-features=ScrollableTabStrip:minTabWidth/140,TabScrollingButtonPosition:buttonPosition/2,kScrollableTabStripOverflow:tabScrollOverflow/2,kScrollableTabStripWithDragging:tabScrollWithDragMode/2"
EOF
else
  #tab_scrolling set to false - so remove the file
  if [ -f "${folder}/tab_scrolling" ];then
    status "Removing ${folder}/tab_scrolling"
  fi
  sudo rm -f "${folder}/tab_scrolling"
fi

#Google sync
if [ "$google_sync" == TRUE ];then
  #add a file from official Debian version of the chromium package
  echo "Adding GOOGLE_API_KEY, GOOGLE_DEFAULT_CLIENT_ID, and GOOGLE_DEFAULT_CLIENT_SECRET to ${folder}/apikeys"
  
  cat << EOF | sudo tee "${folder}/apikeys" >/dev/null
# API keys found in chromium source code https://chromium.googlesource.com/experimental/chromium/src/+/b08bf82b0df37d15a822b478e23ce633616ed959/google_apis/google_api_keys.cc

export GOOGLE_API_KEY="AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k"
export GOOGLE_DEFAULT_CLIENT_ID="77185425430.apps.googleusercontent.com"
export GOOGLE_DEFAULT_CLIENT_SECRET="OTJgUOQcT7lO7GsGZq2G4IlT"
EOF
  echo "Adding ${folder}/enable_sync script to enable sync settings when Chromium launches"
  cat << "EOF" | sudo tee "${folder}/enable_sync" >/dev/null
#!/bin/bash

profiles="$(find "$HOME/.config/chromium/" -maxdepth 1 -type d '(' -name Default -o -name 'Profile *' ')' | sed 's+.*/++g')"
echo "$profiles" | while read -r profile ;do
  [ ! -f "$HOME/.config/chromium/$profile/Preferences" ] && continue
  sed -i 's/"signin":{"allowed":false}/"signin":{"allowed":true,"allowed_on_next_startup":true}/g' "$HOME/.config/chromium/$profile/Preferences"
  sed -i 's/"signin":{"allowed":false,"allowed_on_next_startup":false}/"signin":{"allowed":true,"allowed_on_next_startup":true}/g' "$HOME/.config/chromium/$profile/Preferences"
  sed -i 's/"signin":{"AccountReconcilor":{"kDiceMigrationOnStartup2":true},"allowed":false,"allowed_on_next_startup":false}/"signin":{"AccountReconcilor":{"kDiceMigrationOnStartup2":true},"allowed":true,"allowed_on_next_startup":true}/g' "$HOME/.config/chromium/$profile/Preferences"
done
EOF
else
  #google sync set to false, so remove the file
  if [ -f "${folder}/apikeys" ];then
    status "Removing ${folder}/apikeys"
  fi
  #remove the script that enables sync setting
  if [ -f "${folder}/enable_sync" ];then
    status "Removing ${folder}/enable_sync"
  fi
  
  status "Disabling sync settings for all chromium profiles"
  #turn off sync setting for every profile
  profiles="$(find "$HOME/.config/chromium/" -maxdepth 1 -type d '(' -name Default -o -name 'Profile *' ')' | sed 's+.*/++g')"
  IFS=$'\n'
  for profile in $profiles ;do
    [ ! -f "$HOME/.config/chromium/$profile/Preferences" ] && continue
    sed -i 's/"signin":{"allowed":true}/"signin":{"allowed":false,"allowed_on_next_startup":false}/g' "$HOME/.config/chromium/$profile/Preferences"
    sed -i 's/"signin":{"allowed":true,"allowed_on_next_startup":true}/"signin":{"allowed":false,"allowed_on_next_startup":false}/g' "$HOME/.config/chromium/$profile/Preferences"
    sed -i 's/"signin":{"AccountReconcilor":{"kDiceMigrationOnStartup2":true},"allowed":true,"allowed_on_next_startup":true}/"signin":{"AccountReconcilor":{"kDiceMigrationOnStartup2":true},"allowed":false,"allowed_on_next_startup":false}/g' "$HOME/.config/chromium/$profile/Preferences"
  done
  sudo rm -f "${folder}/apikeys" "${folder}/enable_sync"
fi

#performance improvements
if [ "$performance_improvements" == TRUE ];then
  #various chromium flags from https://forums.raspberrypi.com/viewtopic.php?t=199543 - I removed a few because they reduced stability or WebGL performance
  #More flags added from https://www.ghacks.net/2017/02/13/how-to-speed-up-the-vivaldi-web-browser/
  #Some VA-API flags from https://ubuntuhandbook.org/index.php/2022/07/chromium-snap-package-to-finally-get-back-vaapi-hardware-decoding/
  
  flags="--ignore-gpu-blacklist --enable-checker-imaging --cc-scroll-animation-duration-in-seconds=0.6 --disable-quic --enable-tcp-fast-open --enable-experimental-canvas-features --enable-scroll-prediction --enable-simple-cache-backend --max-tiles-for-interest-area=512 --num-raster-threads=4 --default-tile-height=512 --enable-features=VaapiVideoDecoder,VaapiVideoEncoder,ParallelDownloading --disable-features=UseChromeOSDirectVideoDecoder --enable-accelerated-video-decode --enable-low-res-tiling --process-per-site"
  #The --process-per-site flag significantly decreases RAM usage and number of chromium processes, without any noticeable disadvantages.
  #Not using --enable-low-end-device-mode even though it helps, because scrolling image-heavy pages would crash with "background allocation failure" error.
  
  echo "Adding $flags to ${folder}/performance_improvements"
  cat << EOF | sudo tee "${folder}/performance_improvements" >/dev/null
export CHROMIUM_FLAGS="\$CHROMIUM_FLAGS $flags"
EOF
else
  #performance improvements set to false, so remove file
  if [ -f "${folder}/performance_improvements" ];then
    status "Removing ${folder}/performance_improvements"
  fi
  sudo rm -f "${folder}/performance_improvements"
fi

#reduce sd card writes
if [ "$reduce_writes" == TRUE ];then
  #mount chromium files to tmpfs (script will run with user's privileges whenever Chromium is launched)
  #From: https://forums.raspberrypi.com/viewtopic.php?p=1865820
  echo "Adding ${folder}/reduce_writes script to mount cache/ServiceWorker to /dev/shm when Chromium launches"
  cat << "EOF" | sudo tee "${folder}/reduce_writes" >/dev/null
#!/bin/bash

if [ ! -d /dev/shm ];then
  echo 'Better chromium "Reduce Writes" script: cannot mount folders to /dev/shm because that folder is missing!'
else
  rm -rf /dev/shm/chromium
  mkdir -p /dev/shm/chromium
  
  profiles="$(find "$HOME/.config/chromium/" -maxdepth 1 -type d '(' -name Default -o -name 'Profile *' ')' | sed 's+.*/++g')"
  echo "$profiles" | while read -r profile ;do
  
    rm -rf "$HOME/.config/chromium/$profile/Service Worker"
    mkdir -p "/dev/shm/chromium/$profile/serviceWorker"
    ln -s "/dev/shm/chromium/$profile/serviceWorker" "$HOME/.config/chromium/$profile/Service Worker"
  done
  
  mkdir -p /dev/shm/chromium/cache
  rm -rf "$HOME/.cache/chromium"
  ln -s /dev/shm/chromium/cache/ "$HOME/.cache/chromium"
fi
EOF
else
  if [ -f "${folder}/reduce_writes" ];then
    status "Removing ${folder}/reduce_writes"
  fi
  sudo rm -f "${folder}/reduce_writes"
  
  #clean up old symlinks
  profiles="$(find "$HOME/.config/chromium/" -maxdepth 1 -type d '(' -name Default -o -name 'Profile *' ')' | sed 's+.*/++g')"
  IFS=$'\n'
  for profile in $profiles ;do
    if [ -L "$HOME/.config/chromium/$profile/Service Worker" ];then
      rm -rf "$HOME/.config/chromium/$profile/Service Worker"
    fi
  done
  if [ -L "$HOME/.cache/chromium" ];then
    rm -rf "$HOME/.cache/chromium"
  fi
fi

#widevine
if [ "$widevine_possible" == TRUE ] && [ "$widevine" == TRUE ];then
  #install libwidevinecdm0
  if ! package_installed libwidevinecdm0 ;then
    apt_lock_wait
    sudo apt install -y libwidevinecdm0
  fi
elif [ "$widevine_possible" == TRUE ] && [ "$widevine" == FALSE ];then
  #uninstall libwidevinecdm0
  if package_installed libwidevinecdm0 ;then
    apt_lock_wait
    sudo apt purge -y libwidevinecdm0
  fi
fi

if pgrep chromium >/dev/null || pgrep -f chromium-browser >/dev/null ;then
  status "Changes will take effect after you relaunch Chromium."
fi
true
